package com.lianbang.pharmacy.module.search

import android.app.Activity
import android.content.Context
import android.content.Intent

import com.lianbang.pharmacy.R
import cn.ubest.mvvmcore.base.BaseActivity
import com.lianbang.pharmacy.databinding.ActivitySearchBinding
import com.lianbang.pharmacy.module.medicine.list.MedicineListFragment
import com.lianbang.pharmacy.vm.MedicineVM
import kotlinx.android.synthetic.main.activity_search.*

class SearchActivity : BaseActivity<MedicineVM, ActivitySearchBinding>() {
    private val mSearchHistoryFragment by lazy {
        SearchHistoryFragment.newInstance()
    }
    private var mMedicineListFragment: MedicineListFragment? = null

    companion object {
        fun start(context: Context?) {
            context?.also {
                val starter = Intent(it, SearchActivity::class.java)
                if (it !is Activity) {
                    starter.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                it.startActivity(starter)
            }

        }
    }

    override fun initLayout(): Int {
        return R.layout.activity_search
    }

    override fun initData(intent: Intent) {

    }

    override fun initView() {
        btn_back.setOnClickListener {
            onBackPressed()
        }
        btn_search.setOnClickListener {
            val word = et_search.text.toString()
            if (mMedicineListFragment == null) {
                mMedicineListFragment = MedicineListFragment.newInstance(word)
            }
            mMedicineListFragment?.also {
                if (!it.isAdded) {
                    addFragment(R.id.fl_container, it)
                } else {
                    it.refreshList(word)
                }
            }

        }
        addFragment(R.id.fl_container, mSearchHistoryFragment)
    }

    override fun loadData() {

    }
}
